package ru.budget.mobile.data.sources.local

import ru.budget.mobile.core.Response
import ru.budget.mobile.core.ResponseStates
import ru.budget.mobile.data.entities.IncomeData
import ru.budget.mobile.data.sources.IncomeLocalSource
import ru.budget.mobile.data.sources.local.entities.IncomeDB
import ru.budget.mobile.data.sources.local.room.IncomeDAO

class IncomeLocalSourceImpl(
    private val dao: IncomeDAO
): IncomeLocalSource {

    override suspend fun incomeList(): Response<List<IncomeData>> =
        try {
            val data = dao.incomeList().map(mapper)

            if (data.isEmpty()) {
                throw Exception("Список полученный из базы данных пустой")
            } else {
                Response.Success(
                    data = data,
                    state = ResponseStates.SUCCESS
                )
            }
        } catch (exception: Exception) {
            Response.Error(
                exception = exception,
                state = ResponseStates.ERROR
            )
        }

    override suspend fun addIncome(income: IncomeData): Response<Boolean> =
        try {
            val data = dao.addIncome(
                income = IncomeDB(
                    id = income.id,
                    sum = income.sum,
                    datetime = income.datetime
                )
            )
            if (data == -1L) {
                throw Exception("Не удалось добавить доход в базу данных")
            } else {
                Response.Success(
                    data = true,
                    state = ResponseStates.SUCCESS
                )
            }
        } catch (exception: Exception) {
            Response.Error(
                exception = exception,
                state = ResponseStates.ERROR
            )
        }

    private val mapper = { income: IncomeDB ->
        IncomeData(
            id = income.id,
            sum = income.sum,
            datetime = income.datetime
        )
    }

}